package com.ews.onlineexchange.controller;

import java.io.Serializable;
import java.util.List;

import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityGraph;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.ews.onlineexchange.model.Article;
import com.ews.onlineexchange.model.Category;

@Named
@ViewScoped
public class ArticleQueryBean implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	EntityManager entityManager;
	
	private static final int DEFAULT_MAX_RESULTS = 8;
	
	public List<Article> queryFirst(String categoryName) {
		return queryArticle(categoryName, 1);
	}

	public List<Article> queryArticle(String categoryName) {
		return queryArticle(categoryName, DEFAULT_MAX_RESULTS);
	}
	
	private static final String QUERY_ARTICLE_EQL = ""
			+ "	SELECT			article"
			+ "	FROM			Article article"
			+ "	WHERE			article.category.name = :categoryName"
			+ "	AND				article.stat = '1' "
			+ "	AND				article.delFlag = '0' "
			+ "	ORDER BY		article.weight DESC, "
			+ "					article.sort DESC, "
			+ "					article.createDate DESC, "
			+ "					article.id DESC	";
	public List<Article> queryArticle(String categoryName, int maxResults) {
		Query query = entityManager.createQuery(QUERY_ARTICLE_EQL);
		query.setParameter("categoryName", categoryName);
		query.setMaxResults(maxResults);
		EntityGraph<?> entityGraph = entityManager.getEntityGraph( "Article-category-image-articleData" );
		query.setHint( "javax.persistence.loadgraph", entityGraph );		
		
		return query.getResultList();
	}
	
	private static final String QUERY_CATEGORY_EQL = ""
			+ "	SELECT		c "
			+ "	FROM		Category c "
			+ "	WHERE		c.name = :name	";
	public Category findCategory(String name) {
		Query query = entityManager.createQuery(QUERY_CATEGORY_EQL);
		query.setParameter("name", name);		
		List<Category> resultList = query.getResultList();
		if (resultList.size() > 0)
			return resultList.get(0);
		return null;
	}
	
}
